package aplicacion;

import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import dominio.Cliente;
import net.miginfocom.swing.MigLayout;

import java.awt.BorderLayout;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MenuCliente extends JFrame {
	private JPanel panelCentro;
	private JTable table;
	private static String host = "localhost";
	private static int port = 1500;
	
	public MenuCliente() {
		setSize(800, 600);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		getContentPane().setLayout(new BorderLayout(0, 0));
		JButton btbConsultar = new JButton("Consultar");
		cargarTabla();
		btbConsultar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
		        remove(panelCentro);
		        try {
		        	cargarTabla();
					agregarFilas();
				} catch (Exception e) {
					e.printStackTrace();
				}
				panelCentro.revalidate();
				panelCentro.repaint();
				
			}
		});
		getContentPane().add(btbConsultar, BorderLayout.NORTH);	
		setVisible(true);
	}
	
	@SuppressWarnings("serial")
	public void cargarTabla(){
		panelCentro = new JPanel();
		panelCentro.setLayout( new GridLayout() );
		getContentPane().add(panelCentro, BorderLayout.CENTER);		
		String[] columnas = {"ID Cliente","Nombre","Apellido","Usuario",
				"Direccion", "Telefono","Documento", "Email",};
		table = new JTable(new DefaultTableModel(null, columnas){
		    public boolean isCellEditable(int row, int column)
		    {
		      return false;//para que no se puedan editar las celdas
		    }
		});
		JScrollPane scrollPane = new JScrollPane(table);
		panelCentro.add(scrollPane);		
	}
	
	@SuppressWarnings("unchecked")
	void agregarFilas() throws ClassNotFoundException, IOException, SQLException {
		List<Cliente> lista = new ArrayList<Cliente>();
		Socket socket = new Socket(host,port);
		ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
		lista = (ArrayList<Cliente>) ois.readObject();	
		DefaultTableModel defaultModel = (DefaultTableModel) table.getModel(); 
		for (Cliente c : lista){
			defaultModel.addRow(new Object[]{ c.getIdCliente().toString(),
					c.getNombre(),
					c.getApellido(),
					c.getNombreUsuario(),
					//c.getPassword(),
					c.getDireccion(),
					c.getTelefono(),
					c.getDni(),
					c.getEmail(),});
		}
	    table = new JTable(defaultModel);  
	    if(ois != null)	ois.close();
		if(socket != null)	socket.close();
	}
	
}
